const bcrypt = require('bcryptjs')
/**
 * @description: 加密处理
 * @param password {原密码}
 * @param saltTimes {加盐次数}
 * @return: 加密信息
 */
const encrypt = async (password, saltTimes) => {
  const hash = await bcrypt.hashSync(password, saltTimes)
  console.log(hash)
  return hash
}

/**
 * @description: 密码验证
 * @param password 原密码
 * @param hash 加密密码
 * @return:
 */
const validate = async (password, hash) => {
  const match = await bcrypt.compare(password, hash)
  return match
}
// 定义接口返回的数据模型
class BaseModel {
  constructor(data, message) {
    if (typeof data === 'string') {
      this.message = data
      data = null
      message = null
    }
    if (data) {
      this.data = data
    }

    if (message) {
      this.message = message
    }
  }
}
/**
 * @name: 成功返回模块
 * @method:
 * @msg: 成功返回模块
 * @param {type}
 */
class SuccessModel extends BaseModel {
  constructor(data, message) {
    super(data, message)
    this.code = 0
  }
}

/**
 * @name: FengWQ
 * @method:
 * @msg: 失败返回模块
 * @param {type}
 */
class ErrorModel extends BaseModel {
  constructor(data, message) {
    super(data, message)
    this.code = 1
  }
}

const queryFilter = params => {
  let searchArr = []
  delete params['limit']
  delete params['page']
  Object.keys(params).map(item => {
    if (item) {
      searchArr.push({ item: { $regex: params[item], $options: '$i' } })
    }
  })
  if (searchArr.length) {
    return {
      $or: searchArr
    }
  } else {
    return {}
  }
}

resolvSelectJson = (result, node) => {
  const data = []
  node.forEach(item => {
    let prefix = ''
    for (let i = 0; i < item.level; i++) {
      prefix += '　　'
    }
    data.push({
      id: item.id,
      name: prefix + item.name
    })
    if (result[item.id]) {
      let ret = resolvSelectJson(result, result[item.id])
      ret.forEach(item => {
        let prefix = ''
        for (let i = 0; i < item.level; i++) {
          prefix += '　　'
        }
        data.push({
          id: item.id,
          name: prefix + item.name
        })
      })
    }
  })
  return data
}
module.exports = {
  encrypt,
  validate,
  SuccessModel,
  ErrorModel,
  queryFilter,
  resolvSelectJson
}
